<template style="overflow-y: scroll; overflow-x: hidden; height: 100%">
  <el-drawer
    :title="title"
    size="61%"
    :visible.sync="visibility"
    custom-class="demo-drawer"
  >
    <div class="demo-drawer__content">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="120px"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="来源单号">
              <el-input v-model="temp.sourceOrderCode" :disabled="disabled" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划分装日期">
              <el-date-picker
                v-model="temp.expectManufactureDate"
                :disabled="disabled"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="标签">
              <el-select v-model="temp.tag" :disabled="disabled">
                <el-option
                  v-for="item in tagOptions"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="领料仓库">
              <el-select v-model="temp.fromWarehouseId" :disabled="disabled">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="入库仓库">
              <el-select v-model="temp.toWarehouseId" :disabled="disabled">
                <el-option
                  v-for="item in warehouseOptions"
                  :key="item.key"
                  :label="item.value"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="复溶情况">
              <el-radio-group
                v-model="temp.reconstitutionStatus"
                :disabled="disabled"
              >
                <el-radio :label="0">不复溶</el-radio>
                <el-radio :label="1">通知复溶</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="temp.memo" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="分装前" prop="goodsCode">
          <el-button
            v-if="!disabled"
            icon="el-icon-plus"
            size="mini"
            circle
            class="custome-el-button-circle"
            @click="handleOpenSearchMaterialGoodsDialog"
          />
        </el-form-item>
        <el-form-item>
          <el-table
            v-if="materialGoodsList && materialGoodsList.length > 0"
            :data="materialGoodsList"
            highlight-current-row
            style="margin: 3px"
          >
            <el-table-column label="货号" prop="goodsCode" width="150px" />
            <el-table-column label="货品简称" prop="goodsAbbr" width="120px" />
            <el-table-column label="批号" prop="goodsBatchCode" width="100px" />
            <el-table-column label="浓度" width="120px">
              <template slot-scope="{ row }">
                {{ row.concentration }} {{ row.concentrationUnit }}
              </template>
            </el-table-column>
            <el-table-column
              label="失效日期"
              prop="expirationDate"
              width="100px"
            />
            <el-table-column label="规格" width="150px">
              <template slot-scope="{ row, $index }">
                <el-input
                  v-model="row.specification"
                  type="number"
                  :disabled="disabled"
                  @blur="handleChangeNumber(materialGoodsList, $index, row)"
                >
                  <span slot="append"> {{ row.unit }}</span>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="个数" width="100px">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.expectCount"
                  :disabled="disabled"
                  type="number"
                  onkeyup="value=value.replace(/[^1-9]/g,'')"
                />
              </template>
            </el-table-column>
            <el-table-column label="数量" width="150px">
              <template slot-scope="{ row, $index }">
                <el-input
                  v-model="row.expectQuantity"
                  type="number"
                  :disabled="disabled"
                  @blur="handleChangeNumber(materialGoodsList, $index, row)"
                >
                  <span slot="append"> {{ row.unit }}</span>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="货区"
              prop="warehouseAreaName"
              width="100px"
            />
            <el-table-column
              v-if="!disabled"
              align="center"
              width="100px"
              fixed="right"
            >
              <template slot-scope="{ row }">
                <el-tooltip effect="dark" content="复制" placement="top-start">
                  <el-button
                    icon="el-icon-copy-document"
                    size="mini"
                    circle
                    class="info-color"
                    @click="handleCopyProductionGoods(row)"
                  />
                </el-tooltip>
                <el-tooltip effect="dark" content="删除" placement="top-start">
                  <el-button
                    icon="el-icon-delete"
                    size="mini"
                    circle
                    class="danger-color"
                    @click="handleRemoveMaterialGoods(row)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="分装后" />
        <el-form-item>
          <el-table
            v-if="productionGoodsList && productionGoodsList.length > 0"
            :data="productionGoodsList"
            highlight-current-row
            style="margin: 3px"
          >
            <el-table-column label="货号" prop="goodsCode" width="150px" />
            <el-table-column label="货品简称" prop="goodsAbbr" width="120px" />
            <el-table-column label="批号" prop="goodsBatchCode" width="100px" />
            <el-table-column label="浓度" width="120px">
              <template slot-scope="{ row }">
                {{ row.concentration }} {{ row.concentrationUnit }}
              </template>
            </el-table-column>
            <el-table-column
              label="失效日期"
              prop="expirationDate"
              width="100px"
            />
            <el-table-column label="规格" width="150px">
              <template slot-scope="{ row, $index }">
                <el-input
                  v-model="row.specification"
                  type="number"
                  :disabled="disabled"
                  @blur="handleChangeNumber(productionGoodsList, $index, row)"
                >
                  <span slot="append"> {{ row.unit }}</span>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column label="个数" width="100px">
              <template slot-scope="{ row }">
                <el-input
                  v-model="row.expectCount"
                  :disabled="disabled"
                  type="number"
                  onkeyup="value=value.replace(/[^1-9]/g,'')"
                />
              </template>
            </el-table-column>
            <el-table-column label="数量" width="150px">
              <template slot-scope="{ row, $index }">
                <el-input
                  v-model="row.expectQuantity"
                  type="number"
                  :disabled="disabled"
                  @blur="handleChangeNumber(productionGoodsList, $index, row)"
                >
                  <span slot="append"> {{ row.unit }}</span>
                </el-input>
              </template>
            </el-table-column>
            <el-table-column
              v-if="!disabled"
              align="center"
              width="100px"
              fixed="right"
            >
              <template slot-scope="{ row }">
                <el-tooltip effect="dark" content="复制" placement="top-start">
                  <el-button
                    icon="el-icon-copy-document"
                    size="mini"
                    circle
                    class="info-color"
                    @click="handleCopyProductionGoods(row)"
                  />
                </el-tooltip>
                <el-tooltip effect="dark" content="删除" placement="top-start">
                  <el-button
                    icon="el-icon-delete"
                    size="mini"
                    circle
                    class="danger-color"
                    @click="handleRemoveProductionGoods(row)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <SearchGoods
          :visible.sync="searchGoodsDialogVisible"
          :show-goods-batch="true"
          fetch-goods-batch-mode="all"
          :immediate="false"
          @success="handleSearchGoods"
        />
        <el-form-item v-if="dialogStatus !== 'view'">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="handleCommit"> 确 定 </el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-drawer>
</template>

<script>
import {
  saveManufactureOrder,
  updateManufactureOrder
} from '@/api/mes/manufactureOrder.js'
import { formatDate, getBeginDay } from '@/utils'

import SearchGoods from '@/components/SearchGoods'
import UglyMap from '@/utils/uglyMap'
import { newSort } from '@/utils/common.js'

export default {
  components: { SearchGoods },
  props: {
    visible: {
      required: true,
      type: Boolean
    },
    dialogStatus: {
      required: true,
      type: String
    },
    orderType: {
      type: Number,
      default: null
    },
    tagOptions: {
      type: Array,
      default: null
    },
    warehouseOptions: {
      type: Array,
      default: null
    },
    saveSplitCurrent: {
      type: Object,
      default: null
    }
  },
  data() {
    const isCodeLength = (rule, value, callback) => {
      if (this.materialGoodsList && this.materialGoodsList.length > 0) {
        callback()
      } else {
        return callback(new Error('分装不可为空'))
      }
    }
    return {
      loading: false,
      temp: {
        sourceOrderCode: null,
        tag: null,
        fromWarehouseId: null,
        toWarehouseId: null,
        expectManufactureDate: null,
        reconstitutionStatus: 0,
        memo: null
      },
      materialGoodsList: [],
      productionGoodsList: [],
      searchGoodsMode: null,
      rules: {
        goodsCode: [
          { required: true, validator: isCodeLength, trigger: 'blur' }
        ]
      },
      searchGoodsDialogVisible: false,
      disabled: false,
      title: ''
    }
  },
  computed: {
    visibility: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    }
  },
  watch: {
    visible(value) {
      this.$nextTick(() => {
        if (value) {
          this.temp.orderType = this.orderType
          this.temp.expectManufactureDate = formatDate(getBeginDay(0))
        }
      })
    },
    saveSplitCurrent(data) {
      this.temp = data
      const materialArr = []
      const productionArr = []
      const newArr = data.goodsList || []
      newArr.forEach((e) => {
        if (e.type === 2) {
          materialArr.push(e)
        } else {
          productionArr.push(e)
        }
      })
      this.materialGoodsList = materialArr
      this.productionGoodsList = productionArr
    },
    dialogStatus(value) {
      if (value === 'view') {
        this.disabled = true
        this.title = '查看'
      } else if (value === 'create') {
        this.disabled = false
        this.title = '新建分装通知单'
        this.temp = this.$options.data().temp
        this.materialGoodsList = []
        this.productionGoodsList = []
      } else {
        this.disabled = false
        this.title = '更新分装通知单'
      }
    }
  },
  mounted() {},
  methods: {
    handleOpenSearchMaterialGoodsDialog() {
      this.searchGoodsMode = 'material'
      this.searchGoodsDialogVisible = true
    },
    handleOpenSearchProductionGoodsDialog() {
      this.searchGoodsMode = 'production'
      this.searchGoodsDialogVisible = true
    },
    handleSearchGoods(goods) {
      const currentGoods = Object.assign({}, goods)
      if (this.searchGoodsMode === 'material') {
        this.materialGoodsList.push(currentGoods)
        const currentGoodsCopy = Object.assign({}, goods)
        this.productionGoodsList.push(currentGoodsCopy)
      } else {
        this.productionGoodsList.push(currentGoods)
      }
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate()
      })
    },
    handleRemoveMaterialGoods(row) {
      if (this.materialGoodsList && this.materialGoodsList.length <= 1) {
        this.$message.warning('最少保留一条数据')
      } else {
        this.materialGoodsList.splice(this.materialGoodsList.indexOf(row), 1)
      }
    },
    handleCopyProductionGoods(row) {
      const currentGoodsCopy = Object.assign({}, row)
      currentGoodsCopy.expectQuantity = 0
      currentGoodsCopy.expectCount = 0
      this.productionGoodsList.push(currentGoodsCopy)
      this.productionGoodsList = newSort(this.productionGoodsList, 'goodsCode')
    },
    handleRemoveProductionGoods(row) {
      if (this.productionGoodsList.length <= 1) {
        this.$message.warning('最少保留一条数据')
      } else {
        this.productionGoodsList.splice(
          this.productionGoodsList.indexOf(row),
          1
        )
      }
    },
    handleChangeNumber(list, index, row) {
      if (
        row &&
        row.expectQuantity &&
        row.specification &&
        row.specification > 0
      ) {
        row.expectCount = row.expectQuantity / row.specification
        this.$set(list, index, row)
      }
    },
    handleClose() {
      this.visibility = false
    },
    handleCommit() {
      const goodsList = []
      let msg = null
      const materialMap = new UglyMap()
      this.materialGoodsList.forEach((e) => {
        const quantity = parseInt(
          materialMap.computeIfAbsent(e.goodsCode, (k) => 0)
        )
        materialMap.put(e.goodsCode, quantity + parseInt(e.expectQuantity))
        e.type = 2
        goodsList.push(e)
      })
      const productionMap = new UglyMap()
      this.productionGoodsList.forEach((e) => {
        const quantity = parseInt(
          productionMap.computeIfAbsent(e.goodsCode, (k) => 0)
        )
        productionMap.put(e.goodsCode, quantity + parseInt(e.expectQuantity))
        e.type = 1
        goodsList.push(e)
      })
      materialMap.entries().forEach((e) => {
        const quantity = productionMap.get(e.key)
        if (quantity === null || e.value !== quantity) {
          msg = '货品【' + e.key + '】的数量分装前后不一致'
          return
        }
      })
      if (msg) {
        this.$message.warning(msg)
        return
      }
      this.temp.goodsList = goodsList
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.dialogStatus === 'create') {
            saveManufactureOrder(this.temp).then((response) => {
              this.$emit('save', this.temp)
              this.visibility = false
            })
          } else {
            console.log()
            updateManufactureOrder(this.temp).then((res) => {
              this.$emit('save', this.temp)
              this.visibility = false
              this.$message.success('更新成功')
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss">
</style>
